package issr.market.db.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateFactory  {
	static private SessionFactory _instance;
	
	public static SessionFactory getInstance() {
		if (_instance == null) {
			synchronized (HibernateFactory.class) {
				if (_instance == null) {
					
					Configuration configuration = new Configuration().configure("hibernate.cfg.xml");;
				    ServiceRegistryBuilder serviceRegistryBuilder = new ServiceRegistryBuilder().applySettings(configuration.getProperties());
				    _instance = configuration.buildSessionFactory(serviceRegistryBuilder.buildServiceRegistry());
					//System.out.println("inside...........................");
				}
			}
		}
		return _instance;
	}
	
	public void closeSession(Session hbSession,Transaction tx) {
		if (tx != null && !tx.wasCommitted()) {
			try {
				tx.rollback();
			}
			catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		if (hbSession != null) {
			try {
				hbSession.close();
			}
			catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}
}
